package com.czk.protocol.dubbo;


import com.czk.framework.Invocation;
import com.czk.provider.LocalRegister;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 强转消息
        Invocation invocation = (Invocation) msg;
        // 拿到注册到本地的实现类
        Class serviceImpl = LocalRegister.get(invocation.getInterfaceName());
        // 反射
        Method method = serviceImpl.getMethod(invocation.getMethodName(), invocation.getParamTypes());
        // 执行
        Object result = method.invoke(serviceImpl.newInstance(), invocation.getParams());

        System.out.println("Netty-------------" + result.toString());
        // 返回给客户端
        ctx.writeAndFlush("Netty:" + result);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接断开了");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接进来了");
    }
}
